import 'package:sl_doclever/src/doclever/sl_doc_config.dart';
import 'package:sl_doclever/src/doclever/sl_doc_data.dart';
import 'package:sl_doclever/src/doclever/sl_node.dart';
import 'package:sl_doclever/src/java/sl_java_code.dart';
import 'package:core_extension/core_extension.dart';

class SLJava {
  final SLDocData docData;
  Map outFiles;

  SLJava(this.docData) {
    outFiles = toModelFiles();
  }

  Map toModelFiles() {
    var outMap = {}; // root 节点不要生成

    for (var fNode in docData.allNodesName(docData.outParam)) {
      var outJ = [];

      if (fNode.faterNode == SLDocConfig().root) continue;

      var clsName = fNode.codeType + SLDocConfig().daoEnd.sl_capitalize();

      outJ.add(SLJavaCode.class_begin(
        clsName,
        docData.name,
      ));

      var hasList = false;
      var propertyGetSetList = [];

      docData.outParam.forEach((node) {
        if (fNode.faterNode == node.faterNode) {
          var data_type = '';

          /// 获取到类型中的自定义类名
          if (node.type == SLNodeType.Object || node.type == SLNodeType.Array) {
            for (var i in docData.allNodesName(docData.outParam)) {
              if (node.name == i.faterNode) {
                data_type = i.codeType + SLDocConfig().daoEnd.sl_capitalize();
                break;
              }
            }
          }

          if (node.type == SLNodeType.String) {
            outJ.add(SLJavaCode.property_String(
              node.name,
              node.remark,
            ));
            propertyGetSetList
                .add(SLJavaCode.property_String_get_set(node.name));
          }

          if (node.type == SLNodeType.Object) {
            outJ.add(SLJavaCode.property_Map(
              data_type,
              node.name,
              node.remark,
            ));
            propertyGetSetList
                .add(SLJavaCode.property_Map_get_set(data_type, node.name));
          }

          if (node.type == SLNodeType.Array) {
            hasList = true;
            outJ.add(SLJavaCode.property_List(
              data_type,
              node.name,
              node.remark,
              hasSub: docData.hasSubNodes(docData.outParam, node.name),
            ));
            propertyGetSetList.add(
              SLJavaCode.property_List_get_set(
                data_type,
                node.name,
                hasSub: docData.hasSubNodes(docData.outParam, node.name),
              ),
            );
          }
        }
      });

      outJ.add(propertyGetSetList.join('\n'));
      outJ.add(SLJavaCode.class_end());
      if (hasList) outJ.insert(0, 'import java.util.List;');

      if (SLDocConfig().packageName != null &&
          SLDocConfig().packageName.isNotEmpty) {
        outJ.insert(0, 'package ${SLDocConfig().packageName};\n');
      }

      outMap['$clsName.java'] = outJ.join('\n\n');
    }

    return outMap;
  }
}
